package com.xzl.shop.controller;


import com.xzl.shop.model.User;
import com.xzl.shop.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserServer userServer;
    @Autowired
    private ShopController shopController;
    @RequestMapping("show")
    public ModelAndView select(User user){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("User/show");
        List<User> list = userServer.selectUser(user);
        mv.addObject("list",list);
        return mv;
    }
    @RequestMapping("login")
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("User/login");
        return mv;
    }
    @RequestMapping("toregister")
    public ModelAndView register(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("User/register");
        return mv;
    }
    @RequestMapping("logincheck")
    public ModelAndView loginCheck(User user, HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        if(userServer.selectUser(user).size()>0){
            HttpSession session = request.getSession();
            session.setAttribute("username",user.getPhone());
            Integer id = userServer.selectUser(user).get(0).getId();
            session.setAttribute("userid",id);
            mv = shopController.tonewpage(user,request);
        }
        else{
            mv.setViewName("User/login");
        }
        return mv;
    }
    @RequestMapping("add")
    public ModelAndView add(User user){
        ModelAndView mv = new ModelAndView();
        Integer i = userServer.add(user);
        if(i>0){
            mv = select(new User());
        }
        else {
            mv.setViewName("User/login");
        }
        return mv;
    }
}
